package com.tdam2011.grupo05.ui.activities.contactos;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.CursorWrapper;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.tdam2011.grupo05.R;
import com.tdam2011.grupo05.control.adapters.ContactPhoneAdapter;
import com.tdam2011.grupo05.entities.contact.Contact;
import com.tdam2011.grupo05.ui.activities.LogActivity;

public class ContactosFragment extends ListFragment implements
		LoaderCallbacks<Cursor> {

	protected static final String ORDER_BY = "order_by";
	protected static final String SELECTION = "selection";
	Context context;
	Contact contact;
	private EditText ed;
	SharedPreferences settingFilter;
	SharedPreferences.Editor filterEditor;
	ContactoActivity activityContact;
	ContactosFragment fragment;

	private static final String condition = "((" + Contacts.DISPLAY_NAME
			+ " NOTNULL) AND (" + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
			+ Contacts.DISPLAY_NAME + " LIKE '%";
	private static final String FILTER_STRING = "filterString";
	private static final String[] PROJECTION = new String[] { Contacts._ID,
			Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS,
			Contacts.CONTACT_PRESENCE, Contacts.PHOTO_ID, Contacts.LOOKUP_KEY, };

	private static final String SELECT = "((" + Contacts.DISPLAY_NAME
			+ " NOTNULL) AND (" + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
			+ Contacts.DISPLAY_NAME + " != '' ))";

	interface ListaContactosListener {
		void onChangeOrderListener();

		void onClickContactListener(Contact contact);

		void onFilterChange(String orderBy);
	}

	ImageView mImageView;
	ListaContactosListener listener;
	ContactPhoneAdapter mAdapter;

	public void onAttach(android.app.Activity activity) {
		super.onAttach(activity);
		activityContact = (ContactoActivity) activity;
		context = activity;
		listener = (ListaContactosListener) activity;
		settingFilter = activityContact.getPreferences(Context.MODE_PRIVATE);
	};

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if (mAdapter == null) {
			mAdapter = new ContactPhoneAdapter(getActivity(),
					R.layout.list_item_contacto, null,
					new String[] { Contacts.DISPLAY_NAME },
					new int[] { R.id.nombre_contacto }, 0);
		}
		setListAdapter(mAdapter);

		// setListShown(false);
		getLoaderManager().initLoader(0, getArguments(), this);
		fragment = this;

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.fragment_list_contacts,
				container, false);

		registerForContextMenu(view.findViewById(android.R.id.list));
		// //////////////////FILTRO DE CONTACTOS/////////////////////////////
		ed = (EditText) view.findViewById(R.id.search_box);

		ed.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				filterEditor = settingFilter.edit();
				filterEditor.putString(FILTER_STRING, ed.getText().toString());
				filterEditor.commit();
				Bundle bundle = new Bundle();
				bundle.putString(SELECTION, condition + ed.getText().toString()
						+ "%' ))");
				getLoaderManager().destroyLoader(0);
				getLoaderManager().initLoader(0, bundle, fragment);
			}
		});
		// //////////////////FILTRO DE CONTACTOS/////////////////////////////

		return view;
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {

		if (listener != null) {
			CursorWrapper cw = (CursorWrapper) getListAdapter().getItem(
					position);
			long idContact = cw.getLong(cw.getColumnIndex(Contacts._ID));
//			String nameContact = cw.getString(cw
//					.getColumnIndex(Contacts.DISPLAY_NAME));

			// ///////////////////////////////// METODO BUSQUEDA DE
			// DETALLES////////////////////////////////
			contact = new Contact();
			Cursor mCursor = context.getContentResolver().query(
					ContactsContract.Contacts.CONTENT_URI, null,
					Contacts._ID + " = " + idContact, null, null);
			// Se posiciona en el contacto
			mCursor.moveToNext();
			String name = mCursor.getString(mCursor
					.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
			contact.setId(idContact);
			contact.setNombre(name);
			Cursor phones = context.getContentResolver().query(
					Phone.CONTENT_URI, null,
					Phone.CONTACT_ID + " = " + idContact, null, null);
			// Recorre el array de telefonos agregandolos al objeto
			while (phones.moveToNext()) {
				contact.addPhone(phones.getString(phones
						.getColumnIndex(Phone.NUMBER)));
			}
			phones.close();

			// Recorre el array de emails agregandolos al objeto
			Cursor cursorEmail = context.getContentResolver().query(
					ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
					ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
					new String[] { String.valueOf(idContact) }, null);
			if (cursorEmail != null) {
				while (cursorEmail.moveToNext()) {
					String s = cursorEmail
							.getString(cursorEmail
									.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
					contact.getEmail().add(s);
				}
				cursorEmail.close();
			}
			mCursor.close();

			// ///////////////////////////////// METODO BUSQUEDA DE
			// DETALLES////////////////////////////////

			listener.onClickContactListener(contact);
		}
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle data) {
		String orderBy = Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
		String selection = SELECT;
		if (data.getString(ORDER_BY) != null) {
			orderBy = data.getString(ORDER_BY);
		}

		if (data.getString(SELECTION) != null) {
			selection = data.getString(SELECTION);

		}
		return new CursorLoader(getActivity(), Contacts.CONTENT_URI,
				PROJECTION, selection, null, orderBy);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

		mAdapter.swapCursor(data);
		/*
		 * if (isResumed()) { setListShown(true); } else {
		 * setListShownNoAnimation(true); }
		 */
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		mAdapter.swapCursor(null);
	}

	public ListaContactosListener getListener() {
		return listener;
	}

	public void setListener(ListaContactosListener listener) {
		this.listener = listener;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View view,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, view, menuInfo);
		menu.add(0, 1, 0, "Ver Historial");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		CursorWrapper cw = (CursorWrapper) getListAdapter().getItem(
				info.position);
		long idContact = cw.getLong(cw.getColumnIndex(Contacts._ID));
		String nameContact = cw.getString(cw
				.getColumnIndex(Contacts.DISPLAY_NAME));
		Intent intent = new Intent(getActivity(), LogActivity.class);
		intent.putExtra("idContacto", String.valueOf(idContact));
		intent.putExtra("nombreContacto", nameContact);

		startActivity(intent);
		return true;
	}

}
